import { defineStore } from 'pinia';
import { store } from '@/store';
import { asyncRoutes, basicRoutes } from '@/router/routes'

function hasPermission(route: any, role: any) {
  const routeRole = route.meta?.role ? route.meta.role : []
  if (!role.length || !routeRole.length) {
    return false
  }
  return role.some((item: any) => routeRole.includes(item))
}

function filterAsyncRoutes(routes: any[], role: any) {
  const ret: any[] = []
  routes.forEach((route: any) => {
    // if (hasPermission(route, role)) {
      const curRoute = {
        ...route,
        children: [],
      }
      if (route.children && route.children.length) {
        curRoute.children = filterAsyncRoutes(route.children, role)
      } else {
        Reflect.deleteProperty(curRoute, 'children')
      }
      if(curRoute.name !== undefined){
        ret.push(curRoute)
      }
      // }
  })
  return ret
}

export const usePermissionStore = defineStore('app-permission', {
  state: ()=> ({
      accessRoutes: [],
  }),
  getters: {
    routes(): any[] {
      return basicRoutes.concat(this.accessRoutes);
    },
    menus(): any {
      // console.log(this.routes);
      return this.accessRoutes?.filter((route: any) => route.name && !route.meta?.hidden)
    },
  },
  actions: {
    async generateRoutes(role = []) {
      const accessRoutes: any = filterAsyncRoutes(asyncRoutes, role)
      this.accessRoutes = accessRoutes
      return accessRoutes
    },
  },
});

export function usePermissionStoreWidthOut() {
  return usePermissionStore(store);
};
